package com.fs.ibox.web;

import com.alibaba.fastjson.JSONObject;
import com.fs.ibox.pojo.Collection;
import com.fs.ibox.service.CollectionService;
import com.fs.ibox.service.MarketService;
import com.fs.ibox.util.BeanFactory;
import com.fs.ibox.util.ResponseDataUtil;
import com.fs.ibox.util.ResponseJSONUtil;
import com.fs.ibox.vo.MarketCollection;
import com.fs.ibox.vo.ResponseData;
import jdk.nashorn.internal.ir.debug.JSONWriter;

//import javax.persistence.criteria.CriteriaBuilder;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

import static com.alibaba.fastjson.JSON.toJSONString;

@WebServlet(name = "MarketServlet", value = "/MarketServlet/*")
public class MarketServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json; charset = UTF-8");
        //获取请求路径
        String path = req.getPathInfo();
        if("/queryAll".equals(path)) {
            queryAll(req, resp);
        } else if ("/queryById".equals(path)) {
            queryById(req, resp);
        }
    }

    private void queryAll(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //工厂模式创建一个Service
        MarketService bean = BeanFactory.createBean(MarketService.class);

        String username = req.getParameter("user");

        List<MarketCollection> marketCollections = bean.selectMarket(username);

        ResponseData responseData = ResponseDataUtil.buildOk(marketCollections);
        ResponseJSONUtil.responseJSON(responseData, resp);


    }
    private void queryById(HttpServletRequest request, HttpServletResponse response) throws IOException {
        MarketService bean = BeanFactory.createBean(MarketService.class);
        String idStr = request.getParameter("id");
        int id = Integer.parseInt(idStr);
        MarketCollection marketCollection = bean.selectMarketById(id);


        ResponseData responseData = ResponseDataUtil.buildOk(marketCollection);
        System.out.println(toJSONString(responseData));
        ResponseJSONUtil.responseJSON(responseData, response);
    }
}
